﻿using CommandService;
using Entity.FrameEntity;
using Entity;
using SysFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tools;
using System.Data;
using Newtonsoft.Json.Linq;
using BLL.Statistics;

namespace BLL
{
    public class ChartBLL : PubMethod
    {
        Commands cmd;
        ReturnResult rsl;
        public ChartBLL()
        {
            cmd = new Commands();
        }
        /// <summary>
        /// 销售发票合计
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="deptCode"></param>
        /// <param name="baseCode"></param>
        /// <param name="dateType"></param>
        /// <param name="dataCount"></param>
        /// <returns></returns>
        public ReturnResult SalesTotal(string userCode,string deptCode,string baseCode,string dateType,string dataCount="5")
        {
            rsl = new ReturnResult();
            ERPDatas erpData = new ERPDatas();
            try
            {
                Dictionary<string, object> dic = new Dictionary<string, object>();
                string errMsg = "";
                var erpTable=erpData.SaleBills(dateType, baseCode,"",false,ref errMsg);
                if (!string.IsNullOrWhiteSpace(errMsg))
                {
                    rsl.Message = errMsg; return rsl;
                }
                var sTable= this.SumSalesMark(erpTable, userCode, deptCode, dataCount, ref errMsg);
                if (!string.IsNullOrWhiteSpace(errMsg))
                {
                    rsl.Message = errMsg; return rsl;
                }
                dic["sales"] = cmd.TableToDictionary(sTable);
                sTable = new DataTable();
                errMsg = "";
                sTable = this.SumCustomerMark(erpTable,"7", ref errMsg);
                if (!string.IsNullOrWhiteSpace(errMsg))
                {
                    rsl.Message = errMsg; return rsl;
                }
                dic["customs"] = cmd.TableToDictionary(sTable);
                errMsg = "";
               var list = this.SaleProduct(erpTable,ref errMsg);
                if (!string.IsNullOrWhiteSpace(errMsg))
                {
                    rsl.Message = errMsg; return rsl;
                }
                dic["saleProduct"] = list;
                rsl.Data = dic;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
      
        /// <summary>
        /// 销售存货生产数据统计
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="baseCode"></param>
        /// <param name="dataCount"></param>
        /// <returns></returns>
        public ReturnResult SaleOrderProductTotal(string condition,string baseCode,string dataCount)
        {
            rsl = new ReturnResult();
            try
            {
                ERPDatas erpData = new ERPDatas();
                StringBuilder sb = new StringBuilder();
                string errMsg = "";
                var erpTable = erpData.SaleOrderProduct(baseCode,condition, ref errMsg);
                if (!string.IsNullOrWhiteSpace(errMsg))
                {
                    rsl.Message = errMsg;return rsl;
                }
                erpTable.Columns.Add("pCount");
                foreach (DataRow r in erpTable.Rows)
                {
                    string orderCode = r["orderCode"].ToString();
                    sb.Clear();
                    sb.Append("select isnull(sum(convert(decimal(18,2),number)),'0') number from bar_ProductBarCode_info  ");
                    sb.Append(" where barStatus !='bar-drop' and U8relationCode='" + orderCode +"' and gxCode='ZD'");
                    var barTable = cmd.GetDataTable(sb.ToString());
                    r.BeginEdit();
                    if (barTable.Rows.Count > 0)
                    {
                        r["pCount"] = barTable.Rows[0][0].ToString();
                    }
                    else
                    {
                        r["pCount"] = "0";
                    }
                    r.EndEdit();
                }
                erpTable.DefaultView.Sort = "number desc";
                erpTable = erpTable.DefaultView.ToTable();
                var sTable = erpTable.Clone();
                List<string> reProList = new List<string>();
                List<double> yList = new List<double>();
                List<double> nList = new List<double>();
                List<string> nameList = new List<string>();
                for (int i = 0; i < erpTable.Rows.Count; i++)
                {
                    string proCode = erpTable.Rows[i]["proCode"].ToString();
                    if (!reProList.Contains(proCode))
                    {
                        var dr = erpTable.Select("proCode='"+ proCode +"'");
                        double jhValue =0, scValue =0 ;
                        foreach (DataRow r in dr)
                        {
                            jhValue += double.Parse(r["number"].ToString());
                            scValue+= double.Parse(r["pCount"].ToString());
                        }
                        nameList.Add(erpTable.Rows[i]["proName"].ToString());
                        yList.Add(jhValue);
                        nList.Add(scValue);
                        reProList.Add(proCode);
                        if (reProList.Count == int.Parse(dataCount))
                        {
                            break;
                        }
                    }
                
                   
                }
                Dictionary<string, object> dic = new Dictionary<string, object>();
                dic["names"] = nameList;
                dic["yData"] = yList;
                dic["nData"] = nList;
             
                rsl.Result = true;
                rsl.Data = dic;


            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 销售订单完成进度
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="baseCode"></param>
        /// <param name="dataCount"></param>
        /// <returns></returns>
        public ReturnResult SaleOrderTotal(string condition, string baseCode, string dataCount)
        {
            rsl = new ReturnResult();
            try
            {
                ERPDatas erpData = new ERPDatas();
                StringBuilder sb = new StringBuilder();
                string errMsg = "";
                var erpTable = erpData.SaleOrderProduct(baseCode, condition, ref errMsg);
                if (!string.IsNullOrWhiteSpace(errMsg))
                {
                    rsl.Message = errMsg; return rsl;
                }
                erpTable.Columns.Add("wwcl", typeof(double));//未完成率
                foreach (DataRow r in erpTable.Rows)
                {
                    string orderCode = r["orderCode"].ToString() ;
                    sb.Clear();
                    sb.Append("select isnull(sum(convert(decimal(18,2),number)),'0') number from bar_ProductBarCode_info  ");
                    sb.Append(" where barStatus !='bar-drop' and U8relationCode='" + orderCode + "' and proCode='"+ r["proCode"].ToString() +"'");
                    var barTable = cmd.GetDataTable(sb.ToString());
                    r.BeginEdit();
                    double pCount = 0;
                    if (barTable.Rows.Count > 0 )
                    {
                        pCount =double.Parse(barTable.Rows[0][0].ToString());
                    }
                    r["wwcl"] = Math.Round((double.Parse(r["number"].ToString()) - pCount) / double.Parse(r["number"].ToString()) * 100, 1);
                   
                   
                    r.EndEdit();
                }
                erpTable.DefaultView.Sort = "wwcl desc";
                erpTable = erpTable.DefaultView.ToTable();


                List<Dictionary<string, object>> dList = new List<Dictionary<string, object>>();

                Dictionary<string, object> d;
                foreach (DataRow r in erpTable.Rows)
                {
                    d = new Dictionary<string, object>();
                    d["label"] = r["orderCode"].ToString()+"/" + r["proName"].ToString();
                    double number =double.Parse(r["number"].ToString());
                    double dcl= double.Parse(r["wwcl"].ToString());
                    if(dcl==0)
                    {
                        continue;
                    }
                    d["value"] = dcl;
                    dList.Add(d);
                    if (dList.Count >= int.Parse(dataCount))
                    {
                        break;
                    }
                }

                Dictionary<string, object> dic = new Dictionary<string, object>();
                dic["dlist"] = dList;

                rsl.Result = true;
                rsl.Data = dic;


            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 销售人员业绩汇总
        /// </summary>
        /// <param name="erpDatas">erp数据</param>
        /// <param name="userCode">登录人账号</param>
        /// <param name="userDept">登录人部门</param>
        /// <param name="dataCount">信息条数</param>
        /// <param name="errMsg">错误信息</param>
        /// <returns></returns>
        private DataTable SumSalesMark(DataTable erpDatas,string userCode,string userDept,string dataCount,ref string errMsg)
        {
            DataTable sTable = new DataTable();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from fun_CommonTree_info where trType='dept'");
                if (!string.IsNullOrWhiteSpace(userDept) && userDept != "dept0")
                {
                    sb.Append(" and trCode like'" + userDept + "%'");
                }
                var deptTable = cmd.GetDataTable(sb.ToString());//获取全部部门信息
                #region 判断登录人是否是部门负责人
                bool isManager = false;
                var dr = deptTable.Select("trCode='" + userDept + "'");
                if (dr.Length > 0 && dr[0]["specialFile"] != null && !string.IsNullOrWhiteSpace(dr[0]["specialFile"].ToString()))
                {
                    if (dr[0]["specialFile"].ToString() == userCode)
                    {
                        isManager = true;
                    }
                }
                if (!isManager)
                {
                    errMsg = "无权限查看此数据"; return sTable;
                }
                #endregion
                sb.Clear();
                sb.Append("select * from V_UserInfo where isdel=0");
                var userTable = cmd.GetDataTable(sb.ToString());

                DataTable temTable = new DataTable();
                temTable.Columns.Add("label");
                temTable.Columns.Add("value", typeof(double));
               
                List<string> reList = new List<string>();
                reList.Clear();
                foreach (DataRow r in erpDatas.Rows)
                {
                    string saleUser = r["userCode"].ToString();
                    if (!reList.Contains(saleUser))
                    {
                        string userName = r["userName"].ToString();

                        bool outUser = true;
                        if (r["dept"] != null && !string.IsNullOrWhiteSpace(r["dept"].ToString()))
                        {
                            string s_dept = r["dept"].ToString();
                            dr = deptTable.Select("trCode='" + s_dept + "'");//销售人员部门是否归当前登录人所负责
                            if (dr.Length > 0)
                            {
                                outUser = false;
                            }
                        }
                        if (outUser)
                        {
                            continue;
                        }
                        var d_dr = erpDatas.Select("userCode='" + saleUser + "'");
                        double money = 0;
                        foreach (DataRow ddr in d_dr)
                        {
                            money += double.Parse(ddr["money"].ToString());
                        }
                        DataRow sr = temTable.NewRow();
                        sr["label"] = userName;
                        sr["value"] = Math.Round(money / 10000, 2).ToString();
                        temTable.Rows.Add(sr);
                        reList.Add(saleUser);
                    }



                }
                temTable.DefaultView.Sort = "value desc";
                temTable = temTable.DefaultView.ToTable();
                sTable = temTable.Clone();
                for (int i = 0; i < temTable.Rows.Count; i++)
                {
                    sTable.Rows.Add(temTable.Rows[i].ItemArray);
                    if (i == int.Parse(dataCount) - 1)
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
            }
            return sTable;

        }
       /// <summary>
       /// 客户销售业绩统计
       /// </summary>
       /// <param name="erpDatas">erp数据</param>
       /// <param name="dataCount">信息条数</param>
       /// <param name="errMsg">错误消息</param>
       /// <returns></returns>
        private DataTable SumCustomerMark(DataTable erpDatas,string dataCount, ref string errMsg)
        {
            DataTable sTable = new DataTable();
            try
            {
                DataTable temTable = new DataTable();
                temTable.Columns.Add("name");
                temTable.Columns.Add("value", typeof(double));

                List<string> reList = new List<string>();
                reList.Clear();
                foreach (DataRow r in erpDatas.Rows)
                {
                    string cuCode = r["cuCode"].ToString();
                    if (!reList.Contains(cuCode))
                    {
                        var d_dr = erpDatas.Select("cuCode='" + cuCode + "'");
                        double money = 0;
                        foreach (DataRow ddr in d_dr)
                        {
                            money += double.Parse(ddr["money"].ToString());
                        }
                        DataRow sr = temTable.NewRow();
                        sr["name"] = r["cuName"].ToString();
                        sr["value"] = Math.Round(money / 10000, 2).ToString();
                        temTable.Rows.Add(sr);
                        reList.Add(cuCode);
                    }



                }
                temTable.DefaultView.Sort = "value desc";
                temTable = temTable.DefaultView.ToTable();
                sTable = temTable.Clone();
                for (int i = 0; i < temTable.Rows.Count; i++)
                {
                    sTable.Rows.Add(temTable.Rows[i].ItemArray);
                    if (i == int.Parse(dataCount) - 1)
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
            }
            return sTable;
        }
       /// <summary>
       /// 销售存货金额统计
       /// </summary>
       /// <param name="erpDatas"></param>
       /// <param name="errMsg"></param>
       /// <returns></returns>
        private List<Dictionary<string, object>> SaleProduct(DataTable erpDatas,ref string errMsg)
        {
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            try
            {
                List<string> relist = new List<string>();
                foreach (DataRow r in erpDatas.Rows)
                {
                    if (!relist.Contains(r["proCode"].ToString()))
                    {
                        var dr = erpDatas.Select("proCode='"+ r["proCode"].ToString() + "'");
                        double money = 0;
                        foreach (DataRow qr in dr)
                        {
                            money += double.Parse(qr["money"].ToString());
                        }
                        if (money != 0)
                        {
                            var dic = new Dictionary<string, object>();
                            dic["proName"] = r["proName"].ToString();
                            dic["proCode"] = r["proCode"].ToString();
                            dic["money"] =Math.Round(money,2);
                            list.Add(dic);
                        }
                        relist.Add(r["proCode"].ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
            }
            return list;
        }

        /// <summary>
        /// 进行中工序统计(多饼图格式)
        /// </summary>
        /// <param name="dataCount"></param>
        /// <returns></returns>
        public ReturnResult GongXuFinishCount(string dataCount)
        {
            rsl = new ReturnResult();
            try
            {
                #region 数据获取
                StringBuilder sb = new StringBuilder();
                sb.Append("select parValue from sys_parameters_info where parCode='gxFininsh' ");
                var parTable = cmd.GetDataTable(sb.ToString());
                string gxStr = "";
                if (parTable.Rows.Count > 0 && !string.IsNullOrWhiteSpace(parTable.Rows[0][0].ToString()))
                {
                    gxStr = parTable.Rows[0][0].ToString();
                }
                sb.Clear();
                sb.Append(" select cCode gxCode,cName gxName from fun_CommonData_info where cType='gx' and isdel=0");
                sb.Append(" and cCode in("+ gxStr + ")");
                var gxTable = cmd.GetDataTable(sb.ToString());
                #endregion

                Dictionary<string, object> gdic;
                List<string> reList = new List<string>();
                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                if (string.IsNullOrWhiteSpace(dataCount))
                {
                    dataCount = "5";
                }
                sb.Clear();
                sb.Append("select id,gxCode from pi_ProductionPlan_gx where isdel=0 and isFinish=0");
                var pgTable = cmd.GetDataTable(sb.ToString());
                foreach (DataRow r in gxTable.Rows)
                {
                    if (!reList.Contains(r["gxCode"].ToString()))
                    {
                        var dr = pgTable.Select("gxCode='" + r["gxCode"].ToString() + "'");
                        gdic = new Dictionary<string, object>();
                        gdic["name"] = r["gxName"].ToString();
                        gdic["value"] = dr.Length;
                        list.Add(gdic);
                        reList.Add(r["gxCode"].ToString());
                    }
                    if (reList.Count >= int.Parse(dataCount))
                    {
                        break;
                    }
                }

                rsl.Result = true;
                rsl.Data = list;

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 成品(制袋)存货待入库数量统计
        /// </summary>
        /// <param name="dataCount"></param>
        /// <returns></returns>
        public ReturnResult ChengPinNeedIn(string dataCount)
        { 
            rsl= new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(dataCount))
                {
                    dataCount = "5";
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("select proCode,proName,spec,sum(CONVERT(decimal(18,2),number)) number ");
                sb.Append("from V_BarCode_Info where barStatus='need-in' and gxCode='zd'");
                sb.Append(" group by proCode,proName,spec order by number desc");
                var barTable=cmd.GetDataTable(sb.ToString());
                List<Dictionary<string, object>> dList = new List<Dictionary<string, object>>();
                int i = 0;
                Dictionary<string, object> d;
                foreach (DataRow r in barTable.Rows)
                {
                    i++;
                    d = new Dictionary<string, object>();
                    d["name"] = r["proName"].ToString() + "/" + r["spec"].ToString();
                    d["value"] = double.Parse(r["number"].ToString());
                   

                    dList.Add(d);
                    if (i > int.Parse(dataCount))
                    {
                        break;
                    }
                }
                rsl.Result = true;
                rsl.Data = dList;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
    }
   
}
